const express = require('express');
const { body, validationResult } = require('express-validator');
const { query, transaction } = require('../config/database');
const { authenticateToken } = require('../middleware/auth');

const router = express.Router();

// 获取用户的学习计划列表
router.get('/plans', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    
    const plans = await query(`
      SELECT 
        sp.*,
        COUNT(st.id) as task_count,
        COUNT(CASE WHEN st.is_completed = 1 THEN 1 END) as completed_tasks
      FROM study_plans sp
      LEFT JOIN study_tasks st ON sp.id = st.plan_id
      WHERE sp.user_id = ?
      GROUP BY sp.id
      ORDER BY sp.created_at DESC
    `, [userId]);

    res.json({ success: true, plans });
  } catch (error) {
    console.error('获取学习计划失败:', error);
    res.status(500).json({ success: false, message: '获取学习计划失败' });
  }
});

// 创建学习计划
router.post('/plans', authenticateToken, [
  body('title').notEmpty().withMessage('计划标题不能为空'),
  body('description').notEmpty().withMessage('计划描述不能为空'),
  body('start_date').isISO8601().withMessage('开始日期格式不正确'),
  body('end_date').isISO8601().withMessage('结束日期格式不正确')
], async (req, res) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ success: false, message: errors.array()[0].msg });
    }

    const { title, description, start_date, end_date, priority = 'medium' } = req.body;
    const userId = req.user.id;

    const result = await query(`
      INSERT INTO study_plans (user_id, title, description, start_date, end_date, priority)
      VALUES (?, ?, ?, ?, ?, ?)
    `, [userId, title, description, start_date, end_date, priority]);

    res.json({ 
      success: true, 
      message: '学习计划创建成功',
      plan_id: result.insertId 
    });
  } catch (error) {
    console.error('创建学习计划失败:', error);
    res.status(500).json({ success: false, message: '创建学习计划失败' });
  }
});

// 更新学习计划
router.put('/plans/:id', authenticateToken, [
  body('title').optional().notEmpty().withMessage('计划标题不能为空'),
  body('description').optional().notEmpty().withMessage('计划描述不能为空'),
  body('start_date').optional().isISO8601().withMessage('开始日期格式不正确'),
  body('end_date').optional().isISO8601().withMessage('结束日期格式不正确')
], async (req, res) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ success: false, message: errors.array()[0].msg });
    }

    const planId = req.params.id;
    const userId = req.user.id;
    const updateData = req.body;

    // 检查计划是否存在且属于当前用户
    const plan = await query('SELECT id FROM study_plans WHERE id = ? AND user_id = ?', [planId, userId]);
    if (plan.length === 0) {
      return res.status(404).json({ success: false, message: '学习计划不存在' });
    }

    // 构建更新SQL
    const updateFields = [];
    const updateValues = [];
    
    Object.keys(updateData).forEach(key => {
      if (updateData[key] !== undefined) {
        updateFields.push(`${key} = ?`);
        updateValues.push(updateData[key]);
      }
    });

    if (updateFields.length === 0) {
      return res.status(400).json({ success: false, message: '没有要更新的字段' });
    }

    updateValues.push(planId, userId);
    await query(`
      UPDATE study_plans 
      SET ${updateFields.join(', ')} 
      WHERE id = ? AND user_id = ?
    `, [...updateValues]);

    res.json({ success: true, message: '学习计划更新成功' });
  } catch (error) {
    console.error('更新学习计划失败:', error);
    res.status(500).json({ success: false, message: '更新学习计划失败' });
  }
});

// 删除学习计划
router.delete('/plans/:id', authenticateToken, async (req, res) => {
  try {
    const planId = req.params.id;
    const userId = req.user.id;

    // 检查计划是否存在且属于当前用户
    const plan = await query('SELECT id FROM study_plans WHERE id = ? AND user_id = ?', [planId, userId]);
    if (plan.length === 0) {
      return res.status(404).json({ success: false, message: '学习计划不存在' });
    }

    await query('DELETE FROM study_plans WHERE id = ? AND user_id = ?', [planId, userId]);

    res.json({ success: true, message: '学习计划删除成功' });
  } catch (error) {
    console.error('删除学习计划失败:', error);
    res.status(500).json({ success: false, message: '删除学习计划失败' });
  }
});

// 获取学习计划的任务列表
router.get('/plans/:id/tasks', authenticateToken, async (req, res) => {
  try {
    const planId = req.params.id;
    const userId = req.user.id;

    // 检查计划是否存在且属于当前用户
    const plan = await query('SELECT id FROM study_plans WHERE id = ? AND user_id = ?', [planId, userId]);
    if (plan.length === 0) {
      return res.status(404).json({ success: false, message: '学习计划不存在' });
    }

    const tasks = await query(`
      SELECT * FROM study_tasks 
      WHERE plan_id = ? AND user_id = ?
      ORDER BY created_at ASC
    `, [planId, userId]);

    res.json({ success: true, tasks });
  } catch (error) {
    console.error('获取学习任务失败:', error);
    res.status(500).json({ success: false, message: '获取学习任务失败' });
  }
});

// 添加学习任务
router.post('/plans/:id/tasks', authenticateToken, [
  body('title').notEmpty().withMessage('任务标题不能为空'),
  body('description').optional(),
  body('priority').optional().isIn(['low', 'medium', 'high']).withMessage('优先级必须是low、medium或high'),
  body('estimated_hours').optional().isFloat({ min: 0 }).withMessage('预估时间必须大于0'),
  body('due_date').optional().isISO8601().withMessage('截止日期格式不正确')
], async (req, res) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ success: false, message: errors.array()[0].msg });
    }

    const planId = req.params.id;
    const userId = req.user.id;
    const { title, description, priority = 'medium', estimated_hours, due_date } = req.body;

    // 检查计划是否存在且属于当前用户
    const plan = await query('SELECT id FROM study_plans WHERE id = ? AND user_id = ?', [planId, userId]);
    if (plan.length === 0) {
      return res.status(404).json({ success: false, message: '学习计划不存在' });
    }

    const result = await query(`
      INSERT INTO study_tasks (plan_id, user_id, title, description, priority, estimated_hours, due_date)
      VALUES (?, ?, ?, ?, ?, ?, ?)
    `, [planId, userId, title, description, priority, estimated_hours || null, due_date || null]);

    res.json({ 
      success: true, 
      message: '学习任务添加成功',
      task_id: result.insertId 
    });
  } catch (error) {
    console.error('添加学习任务失败:', error);
    res.status(500).json({ success: false, message: '添加学习任务失败' });
  }
});

// 更新学习任务
router.put('/tasks/:id', authenticateToken, [
  body('title').optional().notEmpty().withMessage('任务标题不能为空'),
  body('description').optional(),
  body('priority').optional().isIn(['low', 'medium', 'high']).withMessage('优先级必须是low、medium或high'),
  body('estimated_hours').optional().isFloat({ min: 0 }).withMessage('预估时间必须大于0'),
  body('actual_hours').optional().isFloat({ min: 0 }).withMessage('实际时间必须大于0'),
  body('due_date').optional().isISO8601().withMessage('截止日期格式不正确'),
  body('is_completed').optional().isBoolean().withMessage('完成状态必须是布尔值')
], async (req, res) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ success: false, message: errors.array()[0].msg });
    }

    const taskId = req.params.id;
    const userId = req.user.id;
    const updateData = req.body;

    // 检查任务是否存在且属于当前用户
    const task = await query('SELECT id FROM study_tasks WHERE id = ? AND user_id = ?', [taskId, userId]);
    if (task.length === 0) {
      return res.status(404).json({ success: false, message: '学习任务不存在' });
    }

    // 如果任务被标记为完成，设置完成时间
    if (updateData.is_completed === true) {
      updateData.completed_at = new Date().toISOString().replace('T', ' ').replace('Z', '');
    } else if (updateData.is_completed === false) {
      updateData.completed_at = null;
    }

    // 构建更新SQL
    const updateFields = [];
    const updateValues = [];
    
    Object.keys(updateData).forEach(key => {
      if (updateData[key] !== undefined) {
        updateFields.push(`${key} = ?`);
        updateValues.push(updateData[key]);
      }
    });

    if (updateFields.length === 0) {
      return res.status(400).json({ success: false, message: '没有要更新的字段' });
    }

    updateValues.push(taskId, userId);
    await query(`
      UPDATE study_tasks 
      SET ${updateFields.join(', ')} 
      WHERE id = ? AND user_id = ?
    `, [...updateValues]);

    res.json({ success: true, message: '学习任务更新成功' });
  } catch (error) {
    console.error('更新学习任务失败:', error);
    res.status(500).json({ success: false, message: '更新学习任务失败' });
  }
});

// 删除学习任务
router.delete('/tasks/:id', authenticateToken, async (req, res) => {
  try {
    const taskId = req.params.id;
    const userId = req.user.id;

    // 检查任务是否存在且属于当前用户
    const task = await query('SELECT id FROM study_tasks WHERE id = ? AND user_id = ?', [taskId, userId]);
    if (task.length === 0) {
      return res.status(404).json({ success: false, message: '学习任务不存在' });
    }

    await query('DELETE FROM study_tasks WHERE id = ? AND user_id = ?', [taskId, userId]);

    res.json({ success: true, message: '学习任务删除成功' });
  } catch (error) {
    console.error('删除学习任务失败:', error);
    res.status(500).json({ success: false, message: '删除学习任务失败' });
  }
});

// 记录学习进度
router.post('/progress', authenticateToken, [
  body('plan_id').isInt().withMessage('计划ID必须是整数'),
  body('task_id').optional().isInt().withMessage('任务ID必须是整数'),
  body('progress_type').isIn(['plan', 'task']).withMessage('进度类型必须是plan或task'),
  body('progress_percentage').isFloat({ min: 0, max: 100 }).withMessage('进度百分比必须在0-100之间'),
  body('study_time').optional().isFloat({ min: 0 }).withMessage('学习时间必须大于0'),
  body('notes').optional()
], async (req, res) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ success: false, message: errors.array()[0].msg });
    }

    const userId = req.user.id;
    const { plan_id, task_id, progress_type, progress_percentage, study_time = 0, notes } = req.body;

    // 检查计划是否存在且属于当前用户
    const plan = await query('SELECT id FROM study_plans WHERE id = ? AND user_id = ?', [plan_id, userId]);
    if (plan.length === 0) {
      return res.status(404).json({ success: false, message: '学习计划不存在' });
    }

    // 如果指定了任务ID，检查任务是否存在
    if (task_id) {
      const task = await query('SELECT id FROM study_tasks WHERE id = ? AND user_id = ?', [task_id, userId]);
      if (task.length === 0) {
        return res.status(404).json({ success: false, message: '学习任务不存在' });
      }
    }

    await query(`
      INSERT INTO study_progress (user_id, plan_id, task_id, progress_type, progress_percentage, study_time, notes)
      VALUES (?, ?, ?, ?, ?, ?, ?)
    `, [userId, plan_id, task_id, progress_type, progress_percentage, study_time, notes]);

    res.json({ success: true, message: '学习进度记录成功' });
  } catch (error) {
    console.error('记录学习进度失败:', error);
    res.status(500).json({ success: false, message: '记录学习进度失败' });
  }
});

module.exports = router;